﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.IO.Ports;

namespace LeTranNam
{
    public partial class SettingSerialPort : Form
    {
        public SettingSerialPort()
        {
            InitializeComponent();
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            StaticValue.PortName = cbPortName.Items[cbPortName.SelectedIndex].ToString();

            ThreadStart ts = new ThreadStart(WriteFile);
            Thread t = new Thread(ts);
            t.Start();
        }

        private void btExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void SettingSerialPort_Load(object sender, EventArgs e)
        {
            try
            {
                String[] portName = SerialPort.GetPortNames();
                if (portName.Length < 1)
                {
                    MessageBox.Show("Không có cổng COM nào trong hệ thống", "Thông báo",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                foreach (String str in portName)
                {
                    cbPortName.Items.Add(str);
                }

                cbParity.SelectedIndex = 0;
                cbPortName.SelectedIndex = 0;
                cbStopBits.SelectedIndex = 0;

            }
            catch (Exception se)
            {
                MessageBox.Show(se.Message);
                MessageBox.Show(se.StackTrace);
            }
        }

        private void WriteFile()
        {
            try
            {
                FileStream fs = File.Create(@"C:\setting.txt");
                pbrProccess.Value = 10;
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(cbPortName.SelectedItem.ToString());
                sw.WriteLine(txtBaudRate.Text);
                pbrProccess.Value = 30;
                sw.WriteLine(txtDataBits.Text);
                sw.WriteLine(cbParity.SelectedItem.ToString());
                sw.WriteLine(cbStopBits.SelectedItem.ToString());
                pbrProccess.Value = 50;
                sw.Flush();
                sw.Close();
                fs.Close();
                pbrProccess.Value = 100;
                MessageBox.Show("Save Information sucessful");
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);                
            }
        }

    }
}
